# -*- coding: utf-8 -*-
import os
import urllib
import config
import parser
import rc4

cache = False

iview_config = None
channels = None

# name, id, url, description
#programme = gtk.TreeStore(str, str, str, str)


class iView:
        programme = []

        def __init__(self, http):
                self.config = config.config()
                self.http = http

                self.config.get_config(self.http.Get(self.config.urls['config_url']))
                
        def fetch_url(self, url):
                """	Simple function that fetches a URL using urllib2.
                        An exception is raised if an error (e.g. 404) occurs.
                """
                #http = urllib2.urlopen(urllib2.Request(url, None, {'User-Agent' : config.user_agent}))
                #http = urllib2.urlopen(url)
                #return http.read()
                
                self.http.SetUserAgent(self.config.user_agent)
                return self.http.Get(url)

        def maybe_fetch(self, url):
                """	Only fetches a URL if it is not in the cache/ directory.
                        In practice, this is really bad, and only useful for saving
                        bandwidth when debugging. For one, it doesn't respect
                        HTTP's wishes. Also, iView, by its very nature, changes daily.
                """

                if not cache:
                        print "The URL: " + str(url)
                        return self.fetch_url(url)


                if not os.path.isdir('cache'):
                        os.mkdir('cache')

                filename = os.path.join('cache', url.split('/')[-1])
                mc.LogError(filename)
                if os.path.isfile(filename):
                        f = open(filename, 'r')
                        data = f.read()
                        f.close()
                else:
                        data = fetch_url(url)
                        f = open(filename, 'w')
                        f.write(data)
                        f.flush()
                        os.fsync(f.fileno())
                        f.close()

                return data


        def get_auth(self):
                """ This function performs an authentication handshake with iView.
                        Among other things, it tells us if the connection is unmetered,
                        and gives us a one-time token we need to use to speak RTSP with
                        ABC's servers, and tells us what the RTMP URL is.
                """
                return parser.parse_auth(self.fetch_url(self.config.urls['auth_url']))

        def get_programmes(self, progress=None):
                """	This function pulls in the index, which contains the TV series
                        that are available to us. The index is possibly encrypted, so we
                        must decrypt it here before passing it to the parser.
                """
		url = str(self.config.urls['index_url'])
		index_data = self.fetch_url(url)

                if self.config.use_encryption:
                        r = rc4.RC4(self.config.index_password)
                        # RC4 is bidirectional, no need to distinguish between 'encrypt'
                        # and 'decrypt'.
                        index_data = r.engine_crypt(r.hex_to_str(index_xml))
		

		#index_data = self.maybe_fetch(url)
		self.programme = parser.parse_index(index_data, useJSON=True)
			

                return self.programme

        def get_series_items(self, series_id):
                """	This function fetches the series detail page for the selected series,
                        which contain the items (i.e. the actual episodes).
                """
                global programme

                series_xml = self.maybe_fetch(self.config.urls['series_url'] % series_id)
                self.episodes = parser.parse_series_items(series_xml)

		return self.episodes


        def get_highlights(self):

                highlightXML = self.maybe_fetch(self.config.urls['highlights_url'])
                return parser.parse_highlights(highlightXML)

        def get_categories(self):
                categoriesXML = str(self.maybe_fetch(self.config.urls['categories_url']))
                return parser.parse_categories(categoriesXML)

	def do_handshake(self):
		handshakeXML = self.fetch_url(self.config.urls['auth_url'])
		return urllib.quote(parser.parse_handshake(handshakeXML))

